import React from 'react';
import { observable, action, toJS } from 'mobx';
import { ListAdvanced, ListViewPage, SearchAdvanced, RouteLayout } from 'weaver-mobile-page';
import { Tools, Toast, Bubble, ActionSheet, Modal } from 'weaver-mobile';
import * as API from './../../apis/monitorApi';
import allStore from './../../stores'
const getLabel = Tools.getLabel;
export class MonitorStore {
    @observable listAdStore = new ListAdvanced.Store({ route: '/monitor', id: 'monitor' })

    @observable showCheck = false;

    @observable leftTreeValueArray = [];

    @observable propsVisiable = false;

    @observable isShowLoading = false;

    @observable noOpenRightParams = {};

    isShowTotal = true;

    @observable totalCount = 0;

    @observable layout_noPermission = new RouteLayout.Store({ route: '/monitor', id: "noPermission" });

    defaultParams = {//默认请求全部数据的请求参数
        fromwhere: "monitor",//从哪儿来
        createdateselect: 0,//创建日期选择
        creatertype: 0,//创建人类型
        gdzt: 0,//归档状态
    }

    workflowData = {};
    scopeList = [];
    nowScope = null;
    @observable hasLoad = false;


    leftTree_params = {};

    constructor() {
        // this.getTotal = this.getTotal.bind(this);
        this.getSopeList = this.getSopeList.bind(this);
    }

    getSopeList=()=> {
        this.scopeList = [
            { scope: 0, operatorText: getLabel(386728, "批量删除"), operatorText_success: getLabel(501360, "批量删除成功"), operatorText_fail: getLabel(501361, "批量删除失败"), operatorApi: "/api/workflow/monitor/delete" },
            { scope: 1, operatorText: getLabel(501362, "批量暂停"), operatorText_success: getLabel(501363, "批量暂停成功"), ooperatorText_fail: getLabel(501364, "批量暂停失败"), operatorApi: "/api/workflow/monitor/stop" },
            { scope: 2, operatorText: getLabel(388099, "批量撤销"), operatorText_success: getLabel(501365, "批量撤销成功"), ooperatorText_fail: getLabel(501366, "批量撤销失败"), operatorApi: "/api/workflow/monitor/cancel" },
            { scope: 3, operatorText: getLabel(385317, "批量启用"), operatorText_success: getLabel(501367, "批量启用成功"), ooperatorText_fail: getLabel(501368, "批量启用失败"), operatorApi: "/api/workflow/monitor/open" },
            { scope: 4, operatorText: getLabel(501369, "批量归档"), operatorText_success: getLabel(501370, "批量归档成功"), ooperatorText_fail: getLabel(501371, "批量归档失败"), operatorApi: "/api/workflow/monitor/archiving" },
        ]
        this.nowScope = this.scopeList[0];
        this.hasLoad = true;
    }


    @action
    setState = (params = {}) => {
        Object.keys(params).forEach((key) => {
            this[key] = params[key];
        });
    }

    /**
      * 请求列表数据的回调函数，得到datakey,并计算总数
      */
     @action
     getDataCallBack = (result) => {
         const { sessionkey = "" } = result;
         this.setTotalCount({ dataKey: sessionkey });
     }


    @action("修改提示的总条数")
    setTotalCount = (params) => {
        API.getDataCount(params).then(res => {
            const { count = 0 } = res;
            this.totalCount = count;
            this.isShowTotal = true;
        })
    }

    /**加载列表数据 */
    loadListData = (isReturn) => {
        let params = { ...this.defaultParams };
        // this.getTotal()//获取总数
        this.setState({ showCheck: false })
        const { listViewStore, searchAdvancedStore } = this.listAdStore;
        if (listViewStore) {
            listViewStore.clearData();
        }
        if (searchAdvancedStore) {//不是点击表单就返回
            const { formParams } = searchAdvancedStore.form;
            params = { ...params, ...formParams };
            // isReturn ? params = { ...params, ...formParams } : "";
            // !isReturn && searchAdvancedStore.form.updateFields(searchAdvancedStore.form.defaultValues)
        }
        this.listAdStore.getData({ url: '/api/workflow/monitor/getSessionkey', method: "POST", params: params },this.getDataCallBack);
    }

    showActionSheet = () => {
        const { listViewStore } = this.listAdStore;
        const { selectedRowKeys = [] } = listViewStore;
        const BUTTONS = [
            {
                content: this.nowScope.operatorText + `（${selectedRowKeys.length}）`,
                onClick: this.batchOperation,
            },
            {
                content: getLabel(201, '取消'),
                onClick: () => console.log('Cancel'),
            },
        ];
        selectedRowKeys.length > 0 && ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps: { onTouchStart: e => e.preventDefault() },
        },
            (buttonIndex) => {
                // console.log("buttonIndex", buttonIndex)
            });
    }

    batchOperation = () => {
        const { listViewStore } = this.listAdStore;
        const { selectedRowKeys = [] } = listViewStore;
        const params = { multiRequestIds: selectedRowKeys.join(",") };
        this.isShowLoading = true;
        Tools.callApi({
            url: this.nowScope.operatorApi,
            params: params,
            method: "POST"
        }).then(results => {
            const { success } = results;
            const { total } = results;
            this.isShowLoading = false;
            if(this.nowScope.scope == 0){
                if(success!=0){
                    if(success == total){
                        //window.workflowMonitorUtil.getMsgContent(data,true,true);
                        Bubble.success(this.nowScope.operatorText_success, 2);
                    }else{
                        this.getMsgContent(results);
                    }
                    this.loadListData(false);;
                } else{
                    this.getMsgContent(results);
                }
            }else{
                if (success) {
                    Bubble.success(this.nowScope.operatorText_success, 2)
                    this.loadListData(false);
                } else {
                    Bubble.success(this.nowScope.ooperatorText_fail, 2)
                }
            }

        })
    }

    getMsgContent(results){
        let successmsg = getLabel(20461,'删除成功！')+results.success+getLabel(18256,'条');
        let errmsgbatch1 = getLabel(20462,'删除失败！') + (results.fail + results.actionfail) + getLabel(18256,'条');
        let errmsgbatch2 = '('+getLabel(522595,'流程删除附加操作')+getLabel(83071,'执行失败')+results.actionfail+getLabel(18256,'条')+')';
        let msg;
        if(results.actionfail){
            msg = (<div><p>{successmsg}</p><p>{errmsgbatch1}</p><p>{errmsgbatch2}</p></div>);
        }else{
            msg = (<div><p>{successmsg}</p><p>{errmsgbatch1}</p></div>);
        }
        //Bubble.success(msg, 2);
        const alert = Modal.alert;
        const alertInstance = alert(getLabel(15172,' 系统提示'), msg, []);
        setTimeout(() => {
            alertInstance.close();
        }, 2500);
    }
}
